$(function() {
    var bdbRelationPlc = {
        /* 初始数据 */
        defData: {
            pageSize: 20, // 每页分页数量.
            domainId: 0, // 域名id.
            layer: 2 // 边缘缓存层id.
        },

        /* 页面状态 */
        pageState: {
            page: 1, // 分页值.
            noData: 'def' // search: 没有匹配的结果; def: 暂无记录.
        },

        /* 添加 */
        addEvent: function() {
            var _this = this,
                formVerify;

            // 表单验证.
            formVerify = $('#bdb-domain-relation-add-form').validate({
                // onkeyup: false,
                errorElement: "div",
                errorPlacement: function (error, element) {
                    error.addClass("help-block");
                    if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
                        error.appendTo(element.parents(".bdb-vc"));
                    } else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: function(form, e) {
                    e.preventDefault();
                    _this.addSave(form, formVerify);
                }
            });

            // 点击添加响应事件.
            $('#bdb-domain-relation-add').off('click').on('click', function() {
                _this.addDefDataProc();
            });

            // 添加取消.
            $('#js-domain-relation-add-cancel').off('click').on('click', function() {
                _this.resetAddForm(formVerify, 'cancel');
            });
        },
        addDefDataProcTpl: function(data) {
            var linesTpl = '',
                domainListTpl = '',
                formEle = $('#bdb-domain-relation-add-form');

            // 线路.
            formEle.find('.bdb-domain-relation-form-lines-container').bdbLinesSelect();
            $.each(data.lineList, function(i, n) {
                linesTpl += '<li data-id="' + i + '">\
                                <span class="left checkNo"></span>\
                                <span class="right">' + n + '</span>\
                            </li>';
            });
            formEle.find('.lines-list ul').html(linesTpl);

            // 记录值.
            formEle.find('.bdb-domain-relation-form-innerid-container').bdbRecordSelect();
            $.each(data.innerDomainList, function(i, n) {
                domainListTpl += '<li class="bdb-ellipsis" data-id="' + n.inner_domain_id + '">' + n.domain_name + '</li>';
            });
            domainListTpl += '<li class="bdb-ellipsis bdb-hide" id="js-recordselect-null" data-id="">没有匹配的数据</li>';
            formEle.find('.record-list ul').html(domainListTpl);

            bdbMain.mLSleep({loading: false}, function() {
                $('#bdb-domain-relation-add-form').fadeIn();
            });
        },
        addDefDataProc: function() {
            var _this = this;
            bdbMain.mLRManag({mask: true, loading: true});
            $.post('/CustomerDomainRelation/initData', {
                domainId: _this.defData.domainId
            }, function(response) {
                if (response.code == 0) {
                    _this.addDefDataProcTpl(response.data);
                } else {
                    bdbMain.mLRManag({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            }, 'json');
        },
        addSave: function(form, formVerify) {
            var _this = this,
                form = $(form),
                params = form.serialize() + '&domainId=' + _this.defData.domainId + '&layer=' + _this.defData.layer;

            // 请求已发出.
            if (!bdbMain.ajaxInfo.state) {
                bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
                return ;
            }

            // 发送请求.
            bdbMain.ajaxInfo.state = 0; // 加锁.
            bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
            $.post('/CustomerDomainRelation/addRelationRecords', params, function(response) {
                if (response.code == 0) {
                    bdbMain.mLRManag({maskDown: 99, alert: {type: 1, msg: '添加成功.'}});
                    _this.resetAddForm(formVerify);
                    bdbMain.mLSleep({}, function() {
                        _this.list();
                    });
                } else {
                    bdbMain.mLSleep({maskDown: 99, loading: false, alert: {type: 2, msg: response.msg}});
                }

                bdbMain.ajaxInfo.state = 1; // 释放锁.
            });
        },

        /* reset add form */
        resetAddForm: function(formVerify, type) {
            var form = $('#bdb-domain-relation-add-form');

            form.find('.form-lines-layer, .form-record-layer').text('请选择');
            form[0].reset();
            formVerify.resetForm();
            form.hide();

            if (type == 'cancel') {
                bdbMain.mLRManag({mask: false});
            }
        },

        /* 列表 */
        listEvent: function() {
            var _this = this;

            $('.bdb-list').off('click.listEvent').on('click.listEvent', function(e) {
                var ele = $(e.target),
                    id = ele.parents('.bdb-list-row').attr('data-id');

                if (ele.hasClass('js-bdb-domain-relation-record-del')) { // 删除.
                    _this.listDel(id);
                } else if (ele.hasClass('js-bdb-domain-relation-record-set')) { // 设置.
                    _this.listSet(id, ele);
                } else if (ele.attr('id') == 'js-domain-relation-edit-cancel') { // 设置-取消.
                    $('.bdb-domain-relation-edit').remove();
                    bdbMain.mLRManag({mask: false});
                }
            });
        },
        listSet: function(id, ele) {
            var _this = this;
            bdbMain.mLRManag({mask: true, loading: true});
            $.post('/CustomerDomainRelation/getRelationRecordDetail', {
                relationId: id
            }, function(response) {
                if (response.code == 0) {
                    bdbMain.mLRManag({loading: false});
                    _this.listSetProc(id, ele, response.data);
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            });
        },
        listSetTpl: function(data, initData) {
            var tpl = '',
                innerDomainList = '';

            $.each(initData.innerDomainList, function(i, n) {
                innerDomainList += '<li class="bdb-ellipsis" data-id="' + n.inner_domain_id + '">' + n.domain_name + '</li>';
            });
            innerDomainList += '<li class="bdb-ellipsis bdb-hide" id="js-recordselect-null" data-id="">没有匹配的数据</li>';

            tpl = '<form class="bdb-hide bdb-domain-relation-edit" id="bdb-domain-relation-edit-form">\
                        <div class="form-group bdb-clearfix">\
                            <div class="bdb-domain-relation-ae-col-1 bdb-f-l bdb-p-r">\
                                <div class="form-lines-layer">' + data.record_line_name + '</div>\
                            </div>\
                            <div class="bdb-domain-relation-ae-col-2 bdb-f-l bdb-p-r">\
                                <div class="bdb-domain-relation-form-innerid-container">\
                                    <input class="form-record" id="innerDomainId-edit" name="innerDomainId" type="text" value="' + data.inner_domain_id + '"\
                                        autocomplete="off" data-rule-required="true" data-msg-required="请选择记录值">\
                                    <div class="bdb-form-select-wrapper bdb-mouse-hover">\
                                        <div class="top-arrow"></div>\
                                        <div class="form-record-layer bdb-ellipsis">' + data.record + '</div>\
                                        <div></div>\
                                        <div class="bdb-hide record-list">\
                                            <div class="search">\
                                                <img class="bdb-mouse-hover" id="search-btn" src="/static/imgs/global/search-white.svg">\
                                                <input type="text" id="record-list-search-input" autocomplete="off" placeholder="请输入要搜索的域名">\
                                            </div>\
                                            <ul>' + innerDomainList + '</ul>\
                                        </div>\
                                        <div class="bottom-arrow"></div>\
                                    </div>\
                                </div>\
                            </div>\
                            <div class="bdb-domain-relation-ae-col-3 bdb-f-l bdb-p-r">\
                                <input class="bdb-domain-relation-form-ttl" id="ttl-edit" name="ttl" type="text" autocomplete="off" value="' + data.ttl + '" \
                                    data-rule-required="true" data-msg-required="请输入TTL" data-rule-digits="true" data-msg-digits="请输入正整数">\
                            </div>\
                            <div class="bdb-domain-relation-ae-col-4 bdb-f-l">\
                                <button class="bdb-btn bdb-btn-444858-s1" type="submit">确定</button>\
                                <button class="bdb-btn bdb-btn-444858-s1" id="js-domain-relation-edit-cancel" type="button">取消</button>\
                            </div>\
                        </div>\
                    </form>';

            return tpl;
        },
        listSetProc: function(id, ele, data) {
            var _this = this,
                setHtml = '';

            $.post('/CustomerDomainRelation/initData', {
                domainId: _this.defData.domainId
            }, function(response) {
                if (response.code == 0) {
                    setHtml = _this.listSetTpl(data, response.data);
                    ele.parents('.bdb-list-row').after(setHtml);
                    _this.listSetVerify(id);
                    $('#bdb-domain-relation-edit-form .bdb-domain-relation-form-innerid-container').bdbRecordSelect();
                    $('#bdb-domain-relation-edit-form').fadeIn();
                } else {
                    bdbMain.mLRManag({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            }, 'json');
        },
        listSetVerify: function(id) {
            var _this = this,
                formVerify;

            // 表单验证.
            formVerify = $('#bdb-domain-relation-edit-form').validate({
                // onkeyup: false,
                errorElement: "div",
                errorPlacement: function (error, element) {
                    error.addClass("help-block");
                    if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
                        error.appendTo(element.parents(".bdb-vc"));
                    } else {
                        error.insertAfter(element);
                    }
                },
                submitHandler: function(form, e) {
                    e.preventDefault();
                    _this.listSetSave(id, form);
                }
            });
        },
        listSetSave: function(id, form) {
            var _this = this,
                form = $(form);

            // 请求已发出.
            if (!bdbMain.ajaxInfo.state) {
                bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
                return ;
            }

            // 发送请求.
            bdbMain.ajaxInfo.state = 0; // 加锁.
            bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
            $.post('/CustomerDomainRelation/updateRelationRecord', {
                relationId: id,
                innerDomainId: form.find('#innerDomainId-edit').val(),
                ttl: form.find('#ttl-edit').val()
            }, function(response){
                if (response.code == 0) {
                    form.remove();
                    bdbMain.mLRManag({maskDown: 99, mask: false, loading: false, alert: {type: 1, msg: '设置成功.'}});
                    bdbMain.mLSleep({}, function() {
                        _this.list();
                    });
                } else {
                    bdbMain.mLSleep({maskDown: 99, loading: false, alert: {type: 2, msg: response.msg}});
                }

                bdbMain.ajaxInfo.state = 1; // 释放锁.
            });

        },
        listDel: function(id) {
            var _this = this;

            bdbMain.confirm({
                textInfo: {
                    content: '确定要删除这条记录吗？',
                    btn: {}
                },
                // note: true,
                params: {
                    url: '/CustomerDomainRelation/deleteRelationRecord',
                    data: {
                        id: id
                    }
                },
                callback: function(ele, params) {
                    _this.listDelCallbackProc(ele, params);
                }
            });
        },
        listDelCallbackProc: function(ele, params) {
            var _this = this;
            ele.hide();

            // 请求已发出.
            if (!bdbMain.ajaxInfo.state) {
                bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
                return ;
            }

            // 发送请求.
            bdbMain.ajaxInfo.state = 0; // 加锁.
            bdbMain.mLRManag({mask: true, loading: true});
            $.post(params.url, {
                relationId: params.data.id,
            }, function(response) {
                if (response.code == 0) {
                    bdbMain.mLRManag({mask: false, loading: false, alert: {type: 1, msg: '删除成功'}});
                    bdbMain.mLSleep({}, function() {
                        _this.list();
                    });
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }

                bdbMain.ajaxInfo.state = 1; // 释放锁.
            });
        },
        listProc: function(data) {
            var tpl = '',
                onOffImg = '',
                state = '',
                operation = '';

            $.each(data.recordList, function(i, n) {
                operation = '<a class="js-bdb-domain-relation-record-set" href="javascript:void(0);">设置</a>';
                if (n.record_line_name != '默认') {
                    operation += '<div class="v-line-ffa007"></div>\
                                 <a class="bdb-f-c-c8baac bdb-mgn-l--1 js-bdb-domain-relation-record-del" href="javascript:void(0);">删除</a>';
                }

                if (n.etcd_status == 1) {
                    state = '有效';
                    onOffImg = 'point-green.svg';
                } else {
                    state = '失效';
                    onOffImg = 'point-red.svg';
                }

                tpl += '<div class="bdb-list-row" data-id="' + n.layer_relation_id + '">\
                            <div class="bdb-mx-w-col-1 bdb-text-align-c"><img src="/static/imgs/global/' + onOffImg + '"></div>\
                            <div class="bdb-mx-w-col-2 bdb-text-align-c">' + n.record_line_name + '</div>\
                            <div class="bdb-mx-w-col-3">' + n.record_type + '</div>\
                            <div class="bdb-mx-w-col-4 bdb-ellipsis">' + n.record + '</div>\
                            <div class="bdb-mx-w-col-5">' + n.ttl + '</div>\
                            <div class="bdb-mx-w-col-6 bdb-text-align-c">' + state + '</div>\
                            <div class="bdb-mx-w-col-7">' + n.create_time + '</div>\
                            <div class="bdb-mx-w-col-8">\
                                <div class="bdb-option-btn bdb-p-r bdb-mgn-t-10">' + operation + '</div>\
                            </div>\
                        </div>';
            });

            return tpl;
        },
        list: function(obj) {
            var _this = this,
                urlParams = bdbMain.getUrlParams();

            bdbMain.mLRManag({mask: true, loading: true});
            _this.defData.domainId = urlParams['id'];

            // 获取列表.
            $.post('/CustomerDomainRelation/getRelationRecordsByLayer', {
                domainId: _this.defData.domainId,
                layer: _this.defData.layer
            }, function(response) {
                var totalRowCnt = 0,
                    listHtml = '';

                if (response.code == 0) {
                    totalRowCnt = parseInt(response.data.totalCount) > 0 ? parseInt(response.data.totalCount) : 0;
                    listHtml = _this.listProc(response.data);
                    _this.listNull(totalRowCnt);
                    $('.bdb-list').html(listHtml);
                    $('.bdb-record-cnt').html(bdbMain.pageInfo.recordCnt.replace('{cnt}', totalRowCnt));
                    bdbMain.mLSleep({mask: false, loading: false});
                } else {
                    bdbMain.mLSleep({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
                }
            });
        },
        listNull: function(totalRowCnt) {
            var noResult = $('.bdb-no-result'),
                noSearchRecord = $('.bdb-no-search-record');

            if (totalRowCnt <= 0) {
                if (this.pageState.noData == 'search') { // 查询.
                    noResult.hide();
                    noSearchRecord.show();
                } else { // 暂无记录.
                    noResult.show();
                    noSearchRecord.hide();
                }
            } else {
                noResult.hide();
                noSearchRecord.hide();
            }
        },

        /* 子导航跳转 */
        subMenuEvent: function() {
            var _this = this;
            $('.subMenu a').off('click').on('click', function() {
                window.location.href = $(this).attr('url') + _this.defData.domainId;
            });
        },

	  	/* 屏幕高度适应 */
	  	contentSizeResize: function () {
			$(window).resize(function() {
                $('.bdb-list').bdbScreenH(3);
			});
		},

        /* 初始化 */
        init: function() {
            var _this = this;

            _this.addEvent();
            _this.list();
            _this.listEvent();
            _this.subMenuEvent();
			_this.contentSizeResize(); // 内容区域屏幕适应.

            $('.bdb-list').bdbScreenH(3); // 右侧列表区域自适应.
        }
    };

    bdbRelationPlc.init();
});
